package com.jfinalnat.httpclient.processor;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;

import com.jfinal.log.Log;

public class GetProcessor extends MethodProcessor {
	
	private static final Log LOG = Log.getLog(Class.class);
	
	public GetProcessor() {
        super();
        // 指向POST请求处理方式
        NEXT_METHOD = new PostProcessor();
    }

    /**
     * 根据ServletRequest生成HttpRequestBase
     * @param request
     * @return
     */
    @Override
    public HttpRequestBase doRequest(HttpServletRequest request) {
        if (request == null || !(request instanceof HttpServletRequest)) {
            return null;
        }

        if (!request.getMethod().equals("GET")) {
            return NEXT_METHOD.doRequest(request);
        } 

        String queryString = "";
        if (request.getQueryString() != null) queryString += "?"+request.getQueryString();
        // 获得目标url
        String url = TARGET_URL + request.getRequestURI()+queryString;
        LOG.info(url);
        // 目标路径为空
        if (url == null || url == "") {
            return null;
        }

        // 创建get请求
    	HttpGet httpGet = new HttpGet(url);
        // 处理请求协议
        httpGet.setProtocolVersion(doProtocol(request));
        // 处理请求头
        httpGet.setHeaders(doHeaders(request));
        
        return httpGet;
    }
    
    /**
     * 根据ServletRequest生成HttpRequestBase
     * @param request
     * @return
     */
    @Override
    public HttpRequestBase doRequest(HttpServletRequest request, String uri) {
    	if (request == null || !(request instanceof HttpServletRequest)) {
    		return null;
    	}
    	
    	if (!request.getMethod().equals("GET")) {
    		return NEXT_METHOD.doRequest(request);
    	} 
    	
    	String queryString = "";
    	if (request.getQueryString() != null) queryString += "?"+request.getQueryString();
    	// 获得目标url
    	String url = TARGET_URL + uri +queryString;
    	System.out.println(url);
    	// 目标路径为空
    	if (url == null || url == "") {
    		return null;
    	}
    	
    	// 创建get请求
    	HttpGet httpGet = new HttpGet(url);
    	// 处理请求协议
    	httpGet.setProtocolVersion(doProtocol(request));
    	// 处理请求头
    	httpGet.setHeaders(doHeaders(request));
    	
    	return httpGet;
    }

}
